package com.scisoft.scan.control.returngoods;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.QueryPageBean;
import com.scisoft.scan.data.returngoods.ReturnGoodsOrderBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_ReturnGoods;

import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class ReturnGoodsOrderActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private TextView bt_undo;
    private TextView bt_done;
    private View v_undo;
    private View v_done;
    private ClearEditText et_bar;
    private String bizId;// 1 未处理 2 已完成

    //分页配置表
    private QueryPageBean pageBean = null;
    private int currentPage = 0;
    float lastY = 0;
    //分页显示控件
    ReturnGoodsOrderAdapter returnGoodsOrderAdapter;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_return_goods_order);
        //页签
        bt_done = findViewById(R.id.bt_done);
        v_undo = findViewById(R.id.v_undo);
        v_done = findViewById(R.id.v_done);
        bt_undo = findViewById(R.id.bt_undo);
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(ReturnGoodsOrderActivity.this, MainMenuActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
                finish();
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryData(true);
            }
        });
        //数据
        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryData(true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        returnGoodsOrderAdapter = new ReturnGoodsOrderAdapter(ReturnGoodsOrderActivity.this);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        returnGoodsOrderAdapter.setItemLayout(R.layout.item_returngoodsorder, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        returnGoodsOrderAdapter.setOnItemClickListener(new ReturnGoodsOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ReturnGoodsOrderBean returnGoodsOrderBean = returnGoodsOrderAdapter.getItemData(position);
                if (returnGoodsOrderBean != null) {
                    Intent intent = new Intent(ReturnGoodsOrderActivity.this, ReturnGoodsDetailActivity.class);
                    intent.putExtra("data", returnGoodsOrderBean);
                    startActivityForResult(intent, 0);
                }
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            returnGoodsOrderAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(returnGoodsOrderAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == returnGoodsOrderAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    returnGoodsOrderAdapter.changeMoreStatus(LOADING_MORE);
                    QueryData(false);
                } else {
                    returnGoodsOrderAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });

        setButton(bt_undo);
    }

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (bizId) {
            case "1":
                setButton(bt_undo);
                break;
            case "2":
                setButton(bt_done);
                break;
        }
    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_undo.getId()) {
            bizId = "1";//未处理
            v_undo.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            bizId = "2";//已完成
            v_undo.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
        QueryData(true);
    }

    //查询新增数据追加到列表尾
    private void QueryData(boolean refresh) {
        CommonUtil.showPress(this);
        QueryTask queryTask = new QueryTask(ReturnGoodsOrderActivity.this, refresh);
        queryTask.execute();
    }

    //查询货架服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        boolean mrefresh = true;
        private List<ReturnGoodsOrderBean> newData = new ArrayList<>();

        QueryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }

                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_ReturnGoods.RETURNGOODS_01(bizId, et_bar.getUpperText().toString());
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_ReturnGoods.RETURNGOODS_02(bizId, et_bar.getUpperText().toString(), pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定数据
    private void BindData(Context context, List<ReturnGoodsOrderBean> newData, boolean refresh) {

        returnGoodsOrderAdapter.clearLeftMenuList();
        if (!refresh) {
            //数据
            if (newData.size() > 0) {
                returnGoodsOrderAdapter.addMoreItem(newData);
            } else {
                returnGoodsOrderAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                returnGoodsOrderAdapter.clearAddItem(newData);
            } else {
                returnGoodsOrderAdapter.clearAddItem(newData);
                returnGoodsOrderAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //适配器相关功能
    class ReturnGoodsOrderAdapter extends CommonAdapter<ReturnGoodsOrderBean> {

        //构造函数
        public ReturnGoodsOrderAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final ReturnGoodsOrderBean returnGoodsOrder, int position) {
            //获取相应索引的ItemBean对象
            final ReturnGoodsOrderBean bean = mList.get(position);
            //设置控件的对应属性值
            TextView tv_orderType = holder.getView(R.id.tv_orderType);
            tv_orderType.setText(bean.orderType);
            TextView tv_no = holder.getView(R.id.tv_no);
            tv_no.setText(bean.orderNo);
            TextView tv_optime = holder.getView(R.id.tv_optime);
            tv_optime.setText(bean.optime);
            TextView tv_supplierName = holder.getView(R.id.tv_supplierName);
            tv_supplierName.setText(bean.customerName);
            TextView tv_amount = holder.getView(R.id.tv_amount);
            tv_amount.setText(bean.amount);
            TextView tv_operator = holder.getView(R.id.tv_operator);
            tv_operator.setText(bean.operator);
            TextView tv_depotName = holder.getView(R.id.tv_depotName);
            tv_depotName.setText(bean.depotName);
            TextView tv_depotAreaName = holder.getView(R.id.tv_depotAreaName);
            tv_depotAreaName.setText(bean.depotAreaName);
            TextView tv_orderInfo = holder.getView(R.id.tv_orderInfo);
            tv_orderInfo.setText(bean.orderInfo);
        }
    }
}
